<?php
if(!defined('app_name')) die('Error entrance.');
class App extends Smarty {

	var $get  = array();
	var $post = array();
	var $tpl;
	var $blDisplay = true; //是否显示模版
	function __construct()
	{
		parent::__construct();
		
		$this->setTemplateDir('./html/templates/');
		$this->setCompileDir('./html/templates_c/');
		$this->setConfigDir('./html/configs/');
		$this->setCacheDir('./html/cache/');
		
		//$this->debugging = true;
		$this->caching = Smarty::CACHING_OFF; //CACHING_LIFETIME_CURRENT;		
		$this->assign('app_name', '50feng');
		$this->assign('cache_time', date("Y-m-d H:i:s"));
		
		$this->setRequest();
		$this->setTemplate();
	}
	
	protected function setTemplate()
	{
		$this->tpl = $this->get['c'].'/'.$this->get['a'].'.tpl';
	}
	
	protected function setRequest()
	{		
		if(!empty($_SERVER['PATH_INFO'])){			
			$pathInfo = explode('/', $_SERVER['PATH_INFO']);
			array_shift($pathInfo); //去除空白
			$this->get['c'] = empty($pathInfo[0]) ? 'Index' : ucfirst($pathInfo[0]);
			array_shift($pathInfo); //去除control
			$this->get['a']  = empty($pathInfo[0]) ? 'index' : strtolower($pathInfo[0]);
			array_shift($pathInfo); //去除action
			for($i=0; $i<count($pathInfo); $i=$i+2){
				if(empty($pathInfo[$i])) continue;
				if($pathInfo[$i] == 'c' || $pathInfo[$i] == 'a') continue;
				$this->get[strtolower($pathInfo[$i])] = strtolower($pathInfo[$i+1]);
			}
		}
		foreach($_GET as $k=>$v){
			if(array_key_exists($k, $this->get)) continue;
			$v = ($k == 'c') ? ucfirst($v) : strtolower($v);
			$k = strtolower($k);	
			$this->get[$k] = $v;
		}
		foreach($_POST as $k=>$v){			
			$this->post[$k] = $v;
		}
		if(!array_key_exists('c', $this->get)) $this->get['c'] = 'Index';
		if(!array_key_exists('a', $this->get))  $this->get['a'] = 'index';
	}
	
	public function error($msg)
	{
		$this->assign("msg", $msg);
		$this->tpl = 'error.tpl';
		$this->html();
		exit;	
	}
	
	public function html()
	{                
		if(!$this->blDisplay) return;		
		if(!$this->templateExists($this->tpl)){
			$this->assign("msg", '模版不存在：'.$this->tpl);
			$this->tpl = 'error.tpl';			
		}
		parent::display($this->tpl);
	}
	
	public function run()
	{		
		$controlFile  = "./app/control/".$this->get['c']."Action.class.php";
		$controlClass = $this->get['c']."Action";
		$action      = $this->get['a'];
		
		
		if(!file_exists($controlFile)){
			$this->html(); exit;
		}else require($controlFile);
		if(!class_exists($controlClass)){			
			$this->html(); exit;
		}	
		
		$this->assign("get", $this->get);
		$this->assign("post", $this->post);
		
		//执行模块
		$m = new $controlClass;
		if(!method_exists($m, $action)){			
			$this->html(); exit;
		}
		$m->$action();		
		$this->html();
	}	
}
?>